package com.zhz.lib.cms.manage.custom;

import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.hibernate.Hibernate;
import org.hibernate.classic.Session;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

import com.zhz.lib.cms.domain.custom.Custom;
import com.zhz.lib.cms.utils.zhz.ZhzSecurityUtil;
import com.zhz.project.common.util.alibaba.StringUtil;
import com.zhz.project.common.util.hibernate.BaseDAO;
import com.zhz.project.common.util.zhzutil.ZhzDateUtil;
import com.zhz.project.common.util.zhzutil.ZhzHttpRequestUtil;
import com.zhz.project.common.util.zhzutil.ZhzStringUtil;

/**
 * 定制模块的处理类
 * 
 * @author liwei2672
 * @version $Id: customAction.java, v 0.1 2010-7-14 下午09:17:08 liwei2672 Exp $
 */
public class customAction extends DispatchAction {

    private static Logger       logger = Logger.getLogger(customAction.class);

    private BaseDAO             baseDao;
    //每页显示的记录数
    private Integer             pageSize;
    //事务模板
    private TransactionTemplate transactionTemplate;

    /**
     * 不给参数，默认执行此处
     */
    public ActionForward unspecified(ActionMapping mapping, ActionForm form,
                                     HttpServletRequest request, HttpServletResponse response)
                                                                                              throws Exception {
        //默认显示定制模块列表
        return customlist(mapping, form, request, response);
    }

    /**
     * 显示定制模块列表
     * 
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public ActionForward customlist(ActionMapping mapping, ActionForm form,
                                    HttpServletRequest request, HttpServletResponse response)
                                                                                             throws Exception {

        //获取选择的定制模块选项
        String radiooption = ZhzHttpRequestUtil.getParameters(request, "radiooption");

        //获取“一级模块列表”
        String leveloneselected = ZhzHttpRequestUtil.getParameters(request, "leveloneselected");

        //获取搜索框的类型
        String keywordType = ZhzHttpRequestUtil.getParameters(request, "keywordType");

        //获取搜索框的值
        String keyword = ZhzHttpRequestUtil.getParameters(request, "keyword");
		String keywordOut = null;
		if (StringUtil.isNotBlank(keyword)) {
			keyword = URLDecoder.decode(keyword);
			keywordOut = URLEncoder.encode(URLEncoder.encode(keyword));
		}

        /////////////////////////////////////////
        //获取页值
        int pageNow = 0;
        String pageNowString = ZhzHttpRequestUtil.getParameters(request, "pageNow");

        if (ZhzStringUtil.isNotNull(pageNowString)) {
            pageNow = Integer.parseInt(pageNowString);
        } else {
            pageNow = 1;
        }
        if (pageNow <= 1)
            pageNow = 1;
        /////////////////////////////////////////

        /////////////////////////////////////////
        //构造查询条件，获得查询结果的数量
        int entryTatal = 0;
        String whereStatement = null;

        //根据搜索框的值进行查询
        if (ZhzStringUtil.isNotNull(keyword)) {
            entryTatal = baseDao.getNumOnQuery(" FROM Custom where ifDelete =0 and " + keywordType
                                               + " like '%" + keyword + "%'");
            whereStatement = "where ifDelete =0 and " + keywordType + " like '%" + keyword + "%'";
        } else {
            entryTatal = baseDao.getNumOnQuery(" FROM Custom where ifDelete =0");
            whereStatement = "where ifDelete =0";
        }

        //根据选择的定制模块选项进行查询
        if (StringUtil.equals(radiooption, "weishenhe")) {
            entryTatal = baseDao
                .getNumOnQuery(" FROM Custom where ifDelete =0 and  aproveState=" + 0);
            whereStatement = "where ifDelete =0 and  aproveState=" + 0;
        } else if (StringUtil.equals(radiooption, "yitongguo")) {
            entryTatal = baseDao
                .getNumOnQuery(" FROM Custom where ifDelete =0 and  aproveState=" + 1);
            whereStatement = "where ifDelete =0 and  aproveState=" + 1;
        } else if (StringUtil.equals(radiooption, "weitongguo")) {
            entryTatal = baseDao
                .getNumOnQuery(" FROM Custom where ifDelete =0 and  aproveState=" + 2);
            whereStatement = "where ifDelete =0 and  aproveState=" + 2;
        }

        if (StringUtil.equals(radiooption, "levelone")) {
            entryTatal = baseDao.getNumOnQuery(" FROM Custom where ifDelete =0  and  level='1'");
            whereStatement = "where ifDelete =0 and  level='1'";
        }
        //根据“一级模块列表”的值进行查询
        if (ZhzStringUtil.isNotNull(leveloneselected))
            if (!leveloneselected.equals("null")) {
                entryTatal = baseDao.getNumOnQuery(" FROM Custom where ifDelete =0 and  sortType='"
                                                   + leveloneselected + "'");
                whereStatement = "where ifDelete =0 and  sortType='" + leveloneselected + "'";
            }

        if (whereStatement == null)
            whereStatement = "";

        int pageTatal = 0;
        if (0 == entryTatal % pageSize) {
            pageTatal = entryTatal / pageSize;
        } else {
            pageTatal = entryTatal / pageSize + 1;
        }

        if (pageNow > pageTatal) {
            pageNow = pageTatal;
        }

        //根据当前页等条件查询
        List<Custom> customlist = (List<Custom>) baseDao.findAllByPage("Custom", whereStatement,
            "order by customId DESC", pageNow, pageSize);

        //将一级模块的列表放入页面
        request.setAttribute("level_arraylist", getSpecLevelList(1));
        //查询的结果集
        request.setAttribute("customlist", customlist);

        request.setAttribute("pageNow", pageNow);
        request.setAttribute("pageSize", pageSize);
        request.setAttribute("pageTatal", pageTatal);
        request.setAttribute("entryTatal", entryTatal);
        request.setAttribute("keyword", keywordOut);
        request.setAttribute("keywordType", keywordType);
        request.setAttribute("radiooption", radiooption);

        return mapping.findForward("custom-list");
    }

    /**
     * 
     * 添加一级模块
     * 
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     */
    public ActionForward customaddlevelone(ActionMapping mapping, ActionForm form,
                                           HttpServletRequest request, HttpServletResponse response) {

        request.setAttribute("writer", ZhzSecurityUtil.getOperatorName());

        //列出所有通过审核的顶级模块
        request.setAttribute("level_arraylist", getCustomByLevelAndApproveState(0, 1));

        return mapping.findForward("custom-add-levelone");
    }

    /**
     * 
     * 保存添加的一级模块
     * 
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     */
    public ActionForward customsavelevelone(ActionMapping mapping, ActionForm form,
                                            HttpServletRequest request, HttpServletResponse response) {

        //获取模块的主内容
        String customcontent = ZhzHttpRequestUtil.getParameters(request, "customcontent");
        //获取标题
        String title = ZhzHttpRequestUtil.getParameters(request, "title");
        //获取父模块
        String levelselected = ZhzHttpRequestUtil.getParameters(request, "levelselected");
        // 获取排序
        String sortNumber = ZhzHttpRequestUtil.getParameters(request, "sortNumber");
        Custom custom = new Custom();

        custom.setTitle(title);
        custom.setContent(customcontent);
        custom.setWriter(ZhzSecurityUtil.getOperatorName());
        custom.setLevel("1");
        custom.setKeyword(null);
        custom.setSortType(levelselected);
        custom.setPubDate(ZhzDateUtil.getYYYYMDDDate(request.getParameter("pubdate")));
        custom.setHit(0);
        custom.setAproveState(0);
        custom.setAproveTime(null);
        custom.setEditor(ZhzSecurityUtil.getOperatorName());
        custom.setEditorTime(new Date());
        custom.setIfDelete(0);
        if (StringUtil.isNotBlank(sortNumber) && StringUtil.isNumeric(sortNumber)) {
            custom.setSortNumber(Integer.valueOf(sortNumber));
        } else {
            custom.setSortNumber(getMaxSortNumber(levelselected));
        }

        boolean x = baseDao.save(custom);

        if (x) {
            request.setAttribute("add", "add");
            request.setAttribute("addresult", x);
        }

        return mapping.findForward("custom-result");
    }


    /**
     * 编辑定制模块
     * 
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     */
    public ActionForward customedit(ActionMapping mapping, ActionForm form,
                                    HttpServletRequest request, HttpServletResponse response) {

        //获取模块id
        String customid = ZhzHttpRequestUtil.getParameters(request, "customid");

        // 获取模块内容
        Custom custom = (Custom) baseDao.findOneObject("Custom", "customId", customid);
        request.setAttribute("custom", custom);

        if (custom.getPubDate() != null) {
            String date = new SimpleDateFormat("yyyy-MM-dd").format(custom.getPubDate());
            request.setAttribute("pubDate", date);
        }

        //获取其父模块
        request.setAttribute("customFather", baseDao.findOneObject("Custom", "customId", custom
            .getSortType()));

        if (StringUtil.equals(custom.getLevel(), "1")) {
            //列出所有通过审核的顶级模块
            request.setAttribute("level_arraylist", getCustomByLevelAndApproveState(0, 1));
            return mapping.findForward("customedit-levelone-form");

        } else if (StringUtil.equals(custom.getLevel(), "2")) {
            //列出所有通过审核的一级模块
            request.setAttribute("level_arraylist", getCustomByLevelAndApproveState(1, 1));
            return mapping.findForward("customedit-leveltwo-form");

        }
        return null;
    }

    /**
     * 保存编辑后的一级模块
     * 
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     */
    public ActionForward customleveloneeditsave(ActionMapping mapping, ActionForm form,
                                                HttpServletRequest request,
                                                HttpServletResponse response) {

        String customid = ZhzHttpRequestUtil.getParameters(request, "customid");

        String customcontent = ZhzHttpRequestUtil.getParameters(request, "customcontent");

        String title = ZhzHttpRequestUtil.getParameters(request, "title");

        String levelselected = ZhzHttpRequestUtil.getParameters(request, "levelselected");
        // 获取排序
        String sortNumber = ZhzHttpRequestUtil.getParameters(request, "sortNumber");

        Custom custom = (Custom) baseDao.findOneObject("Custom", "customId", customid);

        custom.setTitle(title);
        custom.setContent(customcontent);
        custom.setSortType(levelselected);
        custom.setPubDate(ZhzDateUtil.getYYYYMDDDate(request.getParameter("pubdate")));
        custom.setEditor(ZhzSecurityUtil.getOperatorName());
        custom.setEditorTime(new Date());
        if (StringUtil.isNotBlank(sortNumber) && StringUtil.isNumeric(sortNumber)) {
            custom.setSortNumber(Integer.valueOf(sortNumber));
        } else {
            custom.setSortNumber(getMaxSortNumber(levelselected));
        }
        request.setAttribute("edit", true);

        boolean x = baseDao.update(custom);
        if (x) {
            request.setAttribute("edit", "edit");
            request.setAttribute("editresult", x);
        }

        return mapping.findForward("custom-result");
    }


    /**
     * 删除定制模块，其子模块也被删除
     * 
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public ActionForward customdel(ActionMapping mapping, ActionForm form,
                                   final HttpServletRequest request, HttpServletResponse response)
                                                                                                  throws Exception {

        //在一个事务中进行
        String delResult = (String) transactionTemplate.execute(new TransactionCallback() {

            public Object doInTransaction(TransactionStatus status) {

                try {
                    String customidString = ZhzStringUtil.ISOtoUTF8AfterTrimIfNotNull(request
                        .getParameter("customid"));
                    if (ZhzStringUtil.isNotNull(customidString)) {
                        Custom custom = (Custom) baseDao.findOneObject("Custom", "customId",
                            customidString);
                        custom.setIfDelete(1);
                        custom.setEditor(ZhzSecurityUtil.getOperatorName());
                        //将其子模块也删除
                        List<Custom> customlist = baseDao.select("from Custom t where t.sortType= "
                                                                 + customidString);
                        for (Custom c : customlist) {
                            c.setIfDelete(1);
                            custom.setEditor(ZhzSecurityUtil.getOperatorName());
                            custom.setEditorTime(new Date());
                            baseDao.update(c);
                        }
                        baseDao.update(custom);
                    }
                } catch (Exception e) {
                    status.setRollbackOnly();
                    return null;
                }
                return "del";
            }
        });

        if (delResult != null) {
            request.setAttribute("del", "del");
            request.setAttribute("delResult", delResult);
        }
        return mapping.findForward("custom-result");
    }

    /**
     * 
     * 通过ajax请求，获取模块内容
     *
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward customContent(ActionMapping mapping, ActionForm form,
                                       HttpServletRequest request, HttpServletResponse response)
                                                                                                throws Exception {
        String customid = ZhzHttpRequestUtil.getParameters(request, "customid");
        if (ZhzStringUtil.isNotNull(customid)) {
            Custom custom = (Custom) baseDao.findOneObject("Custom", "customId", customid);

            request.setAttribute("custom", custom);
        } else {
            return null;
        }
        return mapping.findForward("custom-content");
    }

    /**
     * 审核定制模块，不影响子模块的审核状态
     * 
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public ActionForward customApprove(ActionMapping mapping, ActionForm form,
                                       HttpServletRequest request, HttpServletResponse response)
                                                                                                throws Exception {

        //获取所有的参数
        Enumeration allParameter = request.getParameterNames();

        // 0 未审核 1 通过 2 不通过
        String aproveState = ZhzStringUtil.ISOtoUTF8AfterTrimIfNotNull(request
            .getParameter("approveState"));

        final int apoveStateInt = Integer.parseInt(aproveState);

        //获取选择的所有待审核的模块
        final Set<String> customIdSet = new HashSet<String>();

        String name = null;
        while (allParameter.hasMoreElements()) {
            name = (String) allParameter.nextElement();
            if (ZhzStringUtil.isNotNull(name) && StringUtil.contains(name, "checkbox")) {
                // 将含有值的checkbox，赋值
                customIdSet.add(request.getParameter(name));
            }
        }

        //在事务中进行
        boolean approveResult = (Boolean) transactionTemplate.execute(new TransactionCallback() {

            public Object doInTransaction(TransactionStatus status) {

                try {
                    Iterator it = customIdSet.iterator();
                    while (it.hasNext()) {
                        String customId = (String) it.next();
                        Custom custom = (Custom) baseDao.findOneObject("Custom", "customId",
                            customId);
                        custom.setAproveState(apoveStateInt);
                        custom.setAproveTime(new Date());
                        custom.setEditor(ZhzSecurityUtil.getOperatorName());
                        custom.setEditorTime(new Date());
                        baseDao.update(custom);
                    }
                } catch (Exception e) {
                    status.setRollbackOnly();
                    return false;
                }
                return true;
            }

        });

        if (approveResult) {
            request.setAttribute("approveResult", approveResult);
            request.setAttribute("app", "app");
        }
        return mapping.findForward("custom-result");
    }

    /**
     * 得到所有的n级模块
     * 
     * @param level     模块级别
     * @return
     */
    public List<String[]> getSpecLevelList(int level) {

        ArrayList<String[]> result = new ArrayList<String[]>();

        //0级模块加入
        result.addAll(getCustomByLevelAndApproveState(level, 0));
        //1级模块加入
        result.addAll(getCustomByLevelAndApproveState(level, 1));

        return result;
    }

    /**
     * 得到符合某种审核状态的所有的n级模块——
     * 
     * @param level         模块级别
     * @param aproveState   审核的状态 
     * @return
     */
    @SuppressWarnings("unchecked")
    public List<String[]> getCustomByLevelAndApproveState(int level, int aproveState) {
        ArrayList<String[]> result = new ArrayList<String[]>();

        List<Custom> list = (List<Custom>) baseDao.select("from Custom where level='" + level
                                                          + "' and aproveState='" + aproveState
                                                          + "' order by customId ASC");
        String[] tempStrings = null;
        // 遍历Custom表中的元素，存于 ArrayList中
        int i = 0;

        if (list != null && list.size() > 0) {
            for (Iterator<Custom> it = list.iterator(); it.hasNext();) {
                Custom ct = (Custom) it.next();
                tempStrings = new String[2];
                tempStrings[0] = ct.getCustomId().toString();
                tempStrings[1] = ct.getTitle();
                result.add(tempStrings);
                i++;
            }
        }
        return result;
    }
    private Integer getMaxSortNumber(String levelselected) {

        if (!StringUtil.isNumericSpace(levelselected)) {
            return 10;
        }
        String sql = "select max(sortNumber) sortNumber from custom where sortType="
                     + levelselected;
        Session session = baseDao.getHibernateTemplate().getSessionFactory().openSession();
        Integer maxId = (Integer) (session.createSQLQuery(sql).addScalar("sortNumber",
            Hibernate.INTEGER)).uniqueResult();
        // 比最大值步进10
        if (maxId != null) {
            return maxId + 10;
        } else {
            return 10;
        }
    }

    public void setPageSize(Integer pageSize) {
        this.pageSize = pageSize;
    }

    public void setBaseDao(BaseDAO baseDao) {
        this.baseDao = baseDao;
    }

    public void setTransactionTemplate(TransactionTemplate transactionTemplate) {
        this.transactionTemplate = transactionTemplate;
    }
}